﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Microsoft.Practices.EnterpriseLibrary.Logging;

using PostSharp.Laos;

using Arquitetura.Architectural.Model;
namespace Arquitetura.Architectural.Aspect
{
    public sealed class SafeCallingAttribute : OnMethodBoundaryAspect
    {
        #region Método(s)
        public override void OnExit(MethodExecutionEventArgs eventArgs)
        {
            if (eventArgs.FlowBehavior == FlowBehavior.RethrowException)
            {
                var returnParam = eventArgs.Method.GetParameters().Where(par => par.IsRetval).FirstOrDefault();
                if (returnParam != null)
                {
                    var returnType = returnParam.ParameterType;
                    if (returnType.IsSubclassOf(typeof(Result)))
                    {
                        eventArgs.ReturnValue = Activator.CreateInstance(returnType);
                        var result = (Result)eventArgs.ReturnValue;
                        result.Messages.Add(new ResultMessage(eventArgs.Exception));
                        result.Success = false;
                    }
                    eventArgs.Exception = null;
                    eventArgs.FlowBehavior = FlowBehavior.Return;
                }
            }
        }
        #endregion Método(s)
    }
}
